package addressbook.test;

import java.util.ArrayList;
import java.util.List;

import org.rococoa.NSObject;
import org.rococoa.Rococoa;
import org.rococoa.cocoa.foundation.NSArray;
import org.rococoa.cocoa.foundation.NSAutoreleasePool;
import org.rococoa.cocoa.foundation.NSString;
import org.rococoa.cocoa.qtkit.QTKit;

import addressbook.model.ABAddressBook;
import addressbook.model.ABPerson;

import com.sun.jna.Native;

/**
 * @author Cyril Joui
 *
 */
public class MacOsAddressBook {

	public static final String abFrameworkName = "AddressBook";

	private static QTKit qtinstance = (QTKit) Native.loadLibrary(abFrameworkName, QTKit.class);

	private NSAutoreleasePool pool;

	/**
	 * 
	 */
	public MacOsAddressBook() {
		pool = NSAutoreleasePool.new_();
	}

	public void releaseAll() {
		pool.drain();
		pool = null;
	}

	public List<ABPerson> findAllPeople() {
		List<ABPerson> peopleList = new ArrayList<ABPerson>();
		System.out.println("starting ...");
		ABAddressBook addressBook = ABAddressBook.CLASS.sharedAddressBook();
		System.out.println("Asking for people");
		NSArray people = addressBook.people();
		for (int i = 0; i < people.count(); i++) {
			NSObject object = people.objectAtIndex(i);
			ABPerson person = Rococoa.cast(object, ABPerson.class);
			// System.out.println("person: " + person);
			String fullName = getNamePartValueForPropert(person, "" + NSString.getGlobalString(abFrameworkName, "kABFirstNameProperty"))
					+ " " + getNamePartValueForPropert(person, "" + NSString.getGlobalString(abFrameworkName, "kABMiddleNameProperty"))
					+ " " + getNamePartValueForPropert(person, "" + NSString.getGlobalString(abFrameworkName, "kABLastNameProperty"));
			System.out.println("Fullname: " + fullName);
			System.out.println("Birthday: "
					+ getNamePartValueForPropert(person, "" + NSString.getGlobalString(abFrameworkName, "kABBirthdayProperty")));
			System.out.println("Email: "
					+ getNamePartValueForPropert(person, "" + NSString.getGlobalString(abFrameworkName, "kABEmailProperty")));
			System.out.println("Phone: "
					+ getNamePartValueForPropert(person, "" + NSString.getGlobalString(abFrameworkName, "kABPhoneProperty")));
			System.out.println("Address: "
					+ getNamePartValueForPropert(person, "" + NSString.getGlobalString(abFrameworkName, "kABAddressProperty")));

			// Add to list
			peopleList.add(person);
		}
		return peopleList;
	}

	/**
	 * @param person
	 * @param property
	 * @return
	 */
	public static String getNamePartValueForPropert(ABPerson person, String property) {
		NSObject valueForProperty = person.valueForProperty(property);
		if (valueForProperty == null) {
			return "";
		}
		return valueForProperty.toString();
	}

}
